package org.chen.user.aop;

import lombok.extern.slf4j.Slf4j;
import org.chen.spring.aop.JoinPoint;
import org.chen.spring.aop.ProceedingJoinPoint;
import org.chen.spring.aop.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * 日志切面
 *
 * @author Chen
 * @since 2023/6/8 15:28
 */
@Aspect
@Slf4j
public class ApiLogAspect {

    @Before("annotation(org.chen.user.annotation.ApiLog)")
    public void before(JoinPoint joinPoint) {
//        log.info("方法：{}，参数：{}", joinPoint.getMethod().getName(), Arrays.toString(joinPoint.getArgs()));
    }

    @Around("annotation(org.chen.user.annotation.ApiLog)")
    public Object around(ProceedingJoinPoint pjp) {
        long start = System.currentTimeMillis();
        Method method = pjp.getMethod();
        ApiLog annotation = method.getAnnotation(ApiLog.class);
        String value = annotation.value();
        Logger logger = LoggerFactory.getLogger(pjp.getMethod().getDeclaringClass());
        logger.info("业务：{}，参数：{}", value, Arrays.toString(pjp.getArgs()));
        Object result = pjp.proceed();
        logger.info("结果：{}", result);
        long end = System.currentTimeMillis();
        logger.info("耗时：{}ms", (end - start));
        return result;
    }

    @After("annotation(org.chen.user.annotation.ApiLog)")
    public void after() {
//        log.info("方法执行完毕");
    }

    @AfterThrowing("annotation(org.chen.user.annotation.ApiLog)")
    public void afterThrowing(Exception e) {
        log.error("出现异常：", e);
    }
}
